package com.roamer.school.web.handler;

import com.roamer.school.common.exception.BusinessException;
import com.roamer.school.common.exception.enums.ExceptionEnum;
import com.roamer.school.common.exception.enums.ResultCode;
import com.roamer.school.web.model.ResultBean;
import com.roamer.school.web.util.ValidateConvertUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;
import java.util.List;

/**
 * 统一异常处理器
 *
 * @author roamer
 * @version V1.0
 * @date 2019/1/21 16:38
 */
@Slf4j
public class BaseExceptionHandler {

    /**
     * 违反约束异常
     */
    protected ResultBean<?> handleConstraintViolationException(ConstraintViolationException ex,
            HttpServletRequest request) {
        log.info("handleConstraintViolationException start, uri:{}, caused by: ", request.getRequestURI(), ex);
        List<ParameterInvalidItem> parameterInvalidItemList = ValidateConvertUtils
                .convertToInvalidItemList(ex.getConstraintViolations());
        return ResultBean.failure(ResultCode.PARAM_IS_INVALID, parameterInvalidItemList);
    }

    /**
     * 处理验证参数封装错误时异常
     */
    protected ResultBean<?> handleConstraintViolationException(HttpMessageNotReadableException ex,
            HttpServletRequest request) {
        log.info("handleConstraintViolationException start, uri:{}, caused by: ", request.getRequestURI(), ex);
        return ResultBean.failure(ResultCode.PARAM_IS_INVALID, ex.getMessage());
    }

    /**
     * 处理参数绑定时异常（反400错误码）
     */
    protected ResultBean<?> handleBindException(BindException ex, HttpServletRequest request) {
        log.info("handleBindException start, uri:{}, caused by: ", request.getRequestURI(), ex);
        List<ParameterInvalidItem> parameterInvalidItemList = ValidateConvertUtils
                .convertToInvalidItemList(ex.getBindingResult());
        return ResultBean.failure(ResultCode.PARAM_IS_INVALID, parameterInvalidItemList);
    }

    /**
     * 处理使用@Validated注解时，参数验证错误异常（反400错误码）
     */
    protected ResultBean<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex,
            HttpServletRequest request) {
        log.info("handleMethodArgumentNotValidException start, uri:{}, caused by: ", request.getRequestURI(), ex);
        List<ParameterInvalidItem> parameterInvalidItemList = ValidateConvertUtils
                .convertToInvalidItemList(ex.getBindingResult());
        return ResultBean.failure(ResultCode.PARAM_IS_INVALID, parameterInvalidItemList);
    }

    /**
     * 处理通用自定义业务异常
     */
    protected ResponseEntity<ResultBean<?>> handleBusinessException(BusinessException ex, HttpServletRequest request) {
        log.info("handleBusinessException start, uri:{}, exception:{}, caused by: {}", request.getRequestURI(),
                 ex.getClass(), ex.getMessage());

        ExceptionEnum exEnum = ExceptionEnum.getByExceptionClass(ex.getClass());
        if (exEnum != null) {
            return ResponseEntity.status(exEnum.getHttpStatus())
                                 .body(ResultBean.failure(exEnum.getResultCode(), ex.getData()));
        }

        return ResponseEntity.status(HttpStatus.OK)
                             .body(ex.getResultCode() == null ? ResultBean.failure(ex.getMessage()) : ResultBean
                                     .failure(ex.getResultCode(), ex.getData()));
    }

    protected ResponseEntity<ResultBean<?>> handleUnauthorizedException(
            UnauthorizedException ex, HttpServletRequest request) {
        log.info("handleUnauthorizedException start, uri:{}, exception:{}, caused by: {}", request.getRequestURI(),
                 ex.getClass(), ex.getMessage());
        return ResponseEntity.status(HttpStatus.OK).body(ResultBean.failure(ResultCode.PERMISSION_NO_ACCESS));
    }

    /**
     * 处理运行时系统异常（反500错误码）
     */
    protected ResultBean<?> handleRuntimeException(RuntimeException ex, HttpServletRequest request) {
        log.error("handleRuntimeException start, uri:{}, caused by: ", request.getRequestURI(), ex);
        //TODO 可通过邮件、微信公众号等方式发送信息至开发人员、记录存档等操作
        return ResultBean.failure(ResultCode.SYSTEM_INNER_ERROR);
    }


}
